package com.project.communitymanagement.auth.common;

import com.project.communitymanagement.entity.TbOwner;
import com.project.communitymanagement.mapper.TbOwnerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private TbOwnerMapper tbOwnerMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        System.out.println(SecurityContextHolder.getContext().getAuthentication());
        TbOwner owner = tbOwnerMapper.getUserByUsername(username);
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_EMPLOYEE");
        grantedAuthorities.add(grantedAuthority);
        return new org.springframework.security.core.userdetails.User(owner.getUsername(), new BCryptPasswordEncoder().encode(owner.getPassword()), grantedAuthorities);
    }
}
